from PyQt5.QtWidgets import QDialog, QFormLayout, QLineEdit, QComboBox, QPushButton


class ConnectionDialog(QDialog):
    def __init__(self, parent=None, is_edit=False, connection_name="", connection_info=None):
        super().__init__(parent)
        self.is_edit = is_edit
        self.connection_name = connection_name
        self.connection_info = connection_info or {}
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("编辑连接" if self.is_edit else "新增连接")
        self.resize(400, 300)

        layout = QFormLayout()

        self.name_input = QLineEdit()
        self.name_input.setText(self.connection_name)
        layout.addRow("连接名称：", self.name_input)

        self.type_input = QComboBox()
        self.type_input.addItems(["MySQL", "PostgreSQL"])
        self.type_input.setCurrentText(self.connection_info.get("type", "MySQL"))
        layout.addRow("数据库类型：", self.type_input)

        self.host_input = QLineEdit()
        self.host_input.setText(self.connection_info.get("host", "localhost"))
        layout.addRow("主机地址：", self.host_input)

        self.port_input = QLineEdit()
        self.port_input.setText(str(self.connection_info.get("port", 3306)))
        layout.addRow("端口：", self.port_input)

        self.user_input = QLineEdit()
        self.user_input.setText(self.connection_info.get("user", ""))
        layout.addRow("用户名：", self.user_input)

        self.password_input = QLineEdit()
        self.password_input.setEchoMode(QLineEdit.Password)
        self.password_input.setText(self.connection_info.get("password", ""))
        layout.addRow("密码：", self.password_input)

        self.database_input = QLineEdit()
        self.database_input.setText(self.connection_info.get("database", ""))
        layout.addRow("数据库名称：", self.database_input)

        self.save_button = QPushButton("保存")
        self.save_button.clicked.connect(self.accept)
        layout.addRow(self.save_button)

        self.setLayout(layout)

    def get_connection_data(self):
        """获取输入的数据库连接信息"""
        connection_name = self.name_input.text()
        connection_info = {
            "type": self.type_input.currentText(),
            "host": self.host_input.text(),
            "port": int(self.port_input.text()),
            "user": self.user_input.text(),
            "password": self.password_input.text(),
            "database": self.database_input.text(),
        }
        return connection_name, connection_info